package com.zhangyan.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhangyan.common.BaseResponse;
import com.zhangyan.common.ErrorCode;
import com.zhangyan.contant.UserConstant;
import com.zhangyan.exception.BusinessException;
import com.zhangyan.model.User;
import com.zhangyan.model.request.UserLoginRequest;
import com.zhangyan.model.request.UserRegisterRequest;
import com.zhangyan.service.UserService;
import com.zhangyan.utils.ResultUtils;
import com.zhangyan.utils.UserUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;

import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

import static com.zhangyan.contant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 *
 * @author zhangyan
 */
//适用于编写restful风格的api,默认返回json
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = {"http://127.0.0.1:3000","http://192.168.34.154:3000/","http://119.3.166.98:8081/","http://172.31.10.13:8081/"}, allowCredentials = "true")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Resource
    private UserService userService;


    //@RequestBody 将前端请求的json与对象关联
    @PostMapping("/register")
    public BaseResponse<String> userRegister(@RequestBody @Param("page") UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户注册请求体为空");
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();

        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword, planetCode)) {
            return null;
        }
        String result = userService.userRegister(userAccount, userPassword, checkPassword, planetCode);
        return ResultUtils.success(result);
    }


    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            return null;
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();


        if (StrUtil.hasBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "request为null");
        }
        User userSession = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userSession != null && userSession.getUserAccount().equals(userAccount)){
            throw new BusinessException(ErrorCode.DUPLICATE_LOGIN, "重复登录");
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        log.info(Arrays.toString(request.getCookies()));
        return ResultUtils.success(user);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "request为null");
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }


    @GetMapping("/search")
    public BaseResponse<Page<User>> searchUser(String username, HttpServletRequest request, int currentPage, int pageSize) {
        //鉴权
        if (isAdmin(request)) throw new BusinessException(ErrorCode.NO_AUTH, "非管理员无法查询数据");
        if (username == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户错误");
        }
        Page<User> users = userService.searchUser(username,currentPage,pageSize);
        return ResultUtils.success(users);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody String id, HttpServletRequest request) {
        //鉴权
        if (isAdmin(request)) throw new BusinessException(ErrorCode.NO_AUTH, "非管理员无法删除数据");
        if (Long.parseLong(id) <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id小于0");
        }
        boolean result = userService.deleteUser(id);
        return ResultUtils.success(result);
    }

    /**
     * 是否为管理员
     * @param request 请求参数
     * @return 布尔
     */
    private boolean isAdmin(HttpServletRequest request) {
        //鉴权
        User user = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (user == null || user.getUserRole() != UserConstant.ADMIN_ROLE) {
            return true;
        }
        return false;
    }

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "获取用户为空");
        }
        String userId = user.getId();

        User byId = UserUtils.userDesensitization(userService.getById(userId));
        log.info("获取用户为{}", byId);
        log.info(Arrays.toString(request.getCookies()));
        return ResultUtils.success(byId);
    }

    /**
     * 修改权限接口
     * @param id 用户id
     * @param request 请求
     * @return 返回
     */
    @PostMapping("/updateAdmin")
    public BaseResponse<Boolean> updateUserByRole(@RequestBody String id, HttpServletRequest request) {
        //鉴权
        if (isAdmin(request)) throw new BusinessException(ErrorCode.NO_AUTH, "非管理员无法修改数据");
        if (Long.parseLong(id) <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id小于0");
        }
        boolean result = userService.updateUserByRole(id);
        return ResultUtils.success(result);
    }

    /**
     * 修改用户接口
     * @param user  用户对象
     * @return 返回是否
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUserByRole(@RequestBody User user, HttpServletRequest request) {

        User user1 = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null || user1 == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "json为空");
        }
        if (!user1.getId().equals(user.getId())){
            throw new BusinessException(ErrorCode.NO_AUTH, "无权限修改他人数据");
        }
        boolean result = userService.updateUser(user);
        return ResultUtils.success(result);
    }

}
